package com.kantboot.system.admin.repository;

import com.kantboot.system.admin.domain.dto.SysAdminRouterSearchDTO;
import com.kantboot.system.admin.domain.entity.SysAdminRouter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface SysAdminRouterRepository extends JpaRepository<SysAdminRouter,Long> {

    @Query("""
    FROM SysAdminRouter AS p
    WHERE
    (:#{#param.id} IS NULL OR p.id = :#{#param.id})
    AND (:#{#param.title} IS NULL OR p.title LIKE CONCAT('%',:#{#param.title},'%'))
    AND (:#{#param.path} IS NULL OR p.path LIKE CONCAT('%',:#{#param.path},'%'))
    AND (:#{#param.componentPath} IS NULL OR p.componentPath LIKE CONCAT('%',:#{#param.componentPath},'%'))
    AND (:#{#param.priority} IS NULL OR p.priority = :#{#param.priority})
    AND (:#{#param.code} IS NULL OR p.code LIKE CONCAT('%',:#{#param.code},'%'))
    AND (:#{#param.parentCode} IS NULL OR p.parentCode LIKE CONCAT('%',:#{#param.parentCode},'%'))
    AND (p.parentCode IS NULL OR p.parentCode = '')
    ORDER BY p.priority DESC
    """)
    Page<SysAdminRouter> getBodyData(
            @Param("param") SysAdminRouterSearchDTO param,
            Pageable pageable
    );

    @Query("""
    FROM SysAdminRouter AS p
    WHERE
    p.parentCode IS NULL OR p.parentCode = ''
    ORDER BY p.priority DESC
    """)
    List<SysAdminRouter> findList();

    /**
     * 根据权限列表获取路由列表
     * @param permissionCodeList
     * @return List<SysAdminRouter>
     */
    @Query("""
    SELECT p
    FROM SysAdminRouter AS p
    LEFT JOIN SysAdminRouterPermission rp
    ON p.code = rp.routerCode
    WHERE rp.permissionCode IN (:permissionCodeList)
    ORDER BY p.priority DESC
    """)
    List<SysAdminRouter> findListByPermissionCodeList(@Param("permissionCodeList") List<String> permissionCodeList);

    /**
     * 根据路由编码获取权限列表，并且只能是最上级路由
     */
    @Query("""
    SELECT p
    FROM SysAdminRouter AS p
    LEFT JOIN SysAdminRouterPermission rp
    ON p.code = rp.routerCode
    WHERE rp.permissionCode IN (:permissionCodeList)
    AND (p.parentCode IS NULL OR p.parentCode = '')
    ORDER BY p.priority DESC
    """)
    List<SysAdminRouter> findTopListByPermissionCodeList(@Param("permissionCodeList") List<String> permissionCodeList);

}